package com.hm.rabitmq.route;

import java.util.Random;
import java.util.UUID;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author shishun.wang
 * @date 2016年12月9日 下午2:42:18
 * @version 1.0
 * @describe 生成log
 */
public class EmitLog {

	private static final String EXCHANGE_NAME = "DIRECT_LOGS";

	private static final String[] LOG_LEVEL = { "info", "warning", "error" };

	private static final Random random = new Random();

	public static void main(String[] args) {
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("115.28.66.183");

			Connection connection = factory.newConnection();
			Channel channel = connection.createChannel();

			// 创建一个直接交换机
			channel.exchangeDeclare(EXCHANGE_NAME, "direct");
			{
				// 在rabbitmq中，生产者不是直接将消息发送给消息队列的，而是将消息交给交换机，由交换机交给队列。
				// 交换机有以下几种类型：direct,topic,headers和fanout
			}

			for (int i = 0; i < 50; i++) {
				String logLevel = getLogLevel();
				String log = i+"---------->this is a log with the level:" + logLevel+";"+UUID.randomUUID();
				channel.basicPublish(EXCHANGE_NAME, logLevel, null, log.getBytes());
				System.out.println("send the log:" + log);
			}

			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 随机获取日志级别
	 */
	private static String getLogLevel() {
		return LOG_LEVEL[random.nextInt(3)];
	}
}
